import { useEffect, useState, useRef } from 'react';
import { MdEditor } from 'md-editor-rt';
import 'md-editor-rt/lib/style.css';
import { useParams } from 'react-router-dom';
import { getBlogContent, uploadImage, updateBlogContent } from '../../api/admin';

const Index = props => {
  const ref = useRef(null);
  let { id } = useParams();
  const [text, setText] = useState('hello md-editor-rt！');

  useEffect(() => {
    if (id) {
      getContent(id);
    }

    console.log(ref, 12312);
    if (ref.current) {
      ref.current.togglePageFullscreen(true);
    }
  }, [id]);

  const getContent = id => {
    getBlogContent(decodeURIComponent(id)).then(res => {
      if (res.code === 200) {
        setText(res.data);
      }
    });
  };

  const handleTextChange = value => {
    setText(value);
  };

  const handleImgUpload = async (files, callback) => {
    const urls = [];
    for (let i = 0; i < files.length; i++) {
      const file = files[i];
      try {
        const res = await uploadImage(file);
        if (res.code === 200 && res.data && res.data.url) {
          urls.push(res.data.url);
        }
      } catch (e) {
        // 可选：处理上传失败
      }
    }
    callback(urls);
  };

  const handleSave = async (v, h) => {
    updateBlogContent({
      path: id ? decodeURIComponent(id) : '',
      content: v,
    }).then(res => {
      window.$message.success('保存成功');
      id && getContent(id);
    });
  };

  return (
    <MdEditor
      ref={ref}
      value={text}
      previewTheme="vuepress"
      onChange={handleTextChange}
      onUploadImg={handleImgUpload}
      onSave={handleSave}
    />
  );
};
export default Index;
